# FastAPI dev server launcher: start server and open browser
param()

$ErrorActionPreference = 'Stop'

# Project root is the parent of this scripts directory
$projRoot = Split-Path -Parent $PSScriptRoot
Set-Location $projRoot

function Test-Server {
    try {
        Invoke-WebRequest -UseBasicParsing -Uri 'http://127.0.0.1:8000/' -TimeoutSec 1 | Out-Null
        return $true
    } catch {
        return $false
    }
}

if (Test-Server) {
    Write-Host 'Server is already running. Opening browser...' -ForegroundColor Green
    Start-Process 'http://127.0.0.1:8000/'
    exit 0
}

Write-Host 'Starting FastAPI dev server...' -ForegroundColor Cyan
Start-Process -FilePath 'python' -ArgumentList '-m uvicorn server:app --reload' -WorkingDirectory $projRoot -WindowStyle Minimized

# Wait for server to come up (max 15s)
$maxWait = 15
$elapsed = 0
while (-not (Test-Server) -and $elapsed -lt $maxWait) {
    Start-Sleep -Seconds 1
    $elapsed++
}

if (Test-Server) {
    Write-Host 'Server ready. Opening browser...' -ForegroundColor Green
    Start-Process 'http://127.0.0.1:8000/'
    exit 0
} else {
    Write-Host 'Server failed to start within timeout.' -ForegroundColor Red
    exit 1
}